/**
 * 路由核心逻辑 - 简化版本
 */
import type { RouteParams, RouterPushOptions, AdPageObject } from './types';
import { RouterMode } from './enums';
import {
  hasOrigin,
  getQueryString,
  addQueryToUrl,
  replaceUrlEnv,
  getRunWithRouteQuerys,
} from '~/utils/router';
import {
  getAppType,
  openAppWebview,
  shouldOpenInNewWebview,
  goBackInApp,
} from '~/utils/app-webview';

// 常量定义
const STATIC_ORIGIN = 'https://static.xinli001.com/msite/index.html';
const PROTOCOLS = {
  YIXINLI: 'yixinli://',
};

/**
 * 路由核心逻辑类
 */
class RouterCore {
  private _router: any = null;
  private _route: any = null;

  constructor() {
    // 简化构造函数，移除不必要的响应式数据
  }

  // 延迟获取路由实例
  private get router() {
    if (!this._router) {
      this._router = useRouter();
    }
    return this._router;
  }

  // 延迟获取路由信息
  private get route() {
    if (!this._route) {
      this._route = useRoute();
    }
    return this._route;
  }

  /**
   * 获取当前环境信息
   */
  private getEnvInfo() {
    return {
      env: process.env.NODE_ENV || 'production',
      origin: window.location.origin,
      href: window.location.href,
    };
  }

  /**
   * 检查是否为APP环境
   */
  private isAppEnv() {
    const { isYixinliApp, isZiXunApp, isQingSuApp, isZiXunShiApp, isCikeApp } =
      getAppType();
    return (
      isYixinliApp || isZiXunApp || isQingSuApp || isZiXunShiApp || isCikeApp
    );
  }

  /**
   * 处理URL - 统一URL处理逻辑
   */
  private processUrl(
    routeParam: string | RouteParams,
    origin: string,
    changeEnv = true
  ): string {
    // 转换为URL字符串
    let url =
      typeof routeParam === 'string'
        ? routeParam
        : this.router.resolve(routeParam).href;

    // 处理内部链接
    const isInternalLink = origin === window.location.href && !hasOrigin(url);

    if (!hasOrigin(url) && !isInternalLink) {
      url = origin + url;
    }

    if (isInternalLink && this.isAppEnv()) {
      url = window.location.origin + url;
    }

    // 环境替换
    if (changeEnv) {
      const { env } = this.getEnvInfo();
      if (env && url.indexOf(env) === -1) {
        url = replaceUrlEnv(url, env);
      }
    }

    // 添加运行时查询参数
    const runWithRouteQuerys = getRunWithRouteQuerys();
    return addQueryToUrl(url, runWithRouteQuerys);
  }

  /**
   * 处理协议跳转
   */
  private handleProtocolJump(url: string): boolean {
    if (url.startsWith(PROTOCOLS.YIXINLI)) {
      window.location.href = url;
      return true;
    }
    return false;
  }

  /**
   * 在APP中打开WebView
   */
  private openInApp(url: string, hideNavigationBar = false): boolean {
    if (!this.isAppEnv()) return false;

    return openAppWebview(url, {
      hideNavigationBar,
      isCurrentPageOpen: 0,
    });
  }

  /**
   * 在小程序中打开页面
   */
  private openInMiniProgram(url: string): boolean {
    const { isWebviewMp } = getAppType();
    if (!isWebviewMp || !window.uniAppNavto) return false;

    window.uniAppNavto.push({
      path: '/pages/webView/webView?src=' + encodeURIComponent(url),
    });
    return true;
  }

  /**
   * 路由跳转主方法
   */
  push(routeParam: string | RouteParams, options: RouterPushOptions = {}) {
    const {
      origin = window.location.href,
      isOpenWebview = true,
      hideNavigationBar = false,
      changeEnv = true,
    } = options;

    const finalIsOpenWebview = shouldOpenInNewWebview(isOpenWebview, true);

    // 处理URL
    let url = this.processUrl(routeParam, origin, changeEnv);

    // 协议跳转直接处理
    if (this.handleProtocolJump(url)) {
      return;
    }

    // 判断是否为内部链接
    const isInternalLink = origin === window.location.href && !hasOrigin(url);

    // 根据环境选择跳转方式
    if (this.isAppEnv() && finalIsOpenWebview) {
      // APP环境：在新WebView中打开
      if (this.openInApp(url, hideNavigationBar)) {
        return;
      }
    } else if (this.openInMiniProgram(url)) {
      // 小程序环境：使用小程序导航
      return;
    } else if (isInternalLink) {
      // 内部链接：使用路由跳转
      const cleanUrl = url.replace(location.origin, '');
      console.log('内部链接跳转:', cleanUrl);
      this.router.push(cleanUrl);
      return;
    }

    // 默认：使用location.href跳转
    console.log('外部链接跳转:', url);
    window.location.href = url;
  }

  /**
   * 路由替换方法 - 简化版本
   */
  replace(routeParam: string | RouteParams, options: RouterPushOptions = {}) {
    const { origin = window.location.href } = options;

    // 处理URL
    let url = this.processUrl(routeParam, origin, true);

    // 判断是否为内部链接
    const isInternalLink = origin === window.location.href && !hasOrigin(url);

    if (isInternalLink) {
      // 内部链接：使用路由替换
      const cleanUrl = url.replace(location.origin, '');
      this.router.replace(cleanUrl);
    } else {
      // 外部链接：使用location.replace
      console.log('外部链接替换:', url);
      window.location.replace(url);
    }
  }

  /**
   * 返回方法 - 简化版本
   */
  goback(isCancelWebview = true) {
    // APP环境：优先使用APP返回逻辑
    if (this.isAppEnv() && isCancelWebview) {
      if (goBackInApp()) {
        return;
      }
    }

    // 小程序环境：使用小程序返回
    const { isWebviewMp } = getAppType();
    if (isWebviewMp && window.uniAppNavto) {
      window.uniAppNavto.back();
      return;
    }

    // 默认：使用路由返回
    this.router.go(-1);
  }

  /**
   * 隐藏导航栏跳转
   */
  pushWithoutNav(
    routeParam: string | RouteParams,
    options: RouterPushOptions = {}
  ) {
    return this.push(routeParam, {
      ...options,
      hideNavigationBar: true,
      isOpenWebview: this.isAppEnv() ? true : options.isOpenWebview,
    });
  }

  /**
   * 跳转到静态页面
   */
  toStatic(routeParam: string | RouteParams, isOpenWebview = true) {
    return this.push(routeParam, {
      origin: STATIC_ORIGIN,
      isOpenWebview: this.isAppEnv() ? true : isOpenWebview,
      mode: RouterMode.HASH,
    });
  }

  /**
   * 跳转到静态页面（隐藏导航栏）
   */
  toStaticWithoutNav(routeParam: string | RouteParams, isOpenWebview = true) {
    return this.push(routeParam, {
      origin: STATIC_ORIGIN,
      isOpenWebview: this.isAppEnv() ? true : isOpenWebview,
      mode: RouterMode.HASH,
      hideNavigationBar: true,
    });
  }

  /**
   * 跳转到登录页面
   */
  toLogin() {
    const { isYixinliApp, isZiXunApp, isQingSuApp, isCikeApp, isWebviewMp } =
      getAppType();

    if (isYixinliApp || isZiXunApp || isQingSuApp || isCikeApp) {
      // APP环境：使用协议跳转
      this.push('yixinli://open_user_login');
    } else {
      // Web环境：跳转到登录页面
      const { env } = this.getEnvInfo();
      const envSuffix = env ? `-${env}` : '';
      const nextUrl = encodeURIComponent(window.location.href);
      const hiddenParam = isWebviewMp ? '&hiddenThirdLogin=true' : '';

      const loginUrl = `https://m${envSuffix}.xinli001.com/account/login?next=${nextUrl}${hiddenParam}`;
      this.push(loginUrl);
    }
  }

  /**
   * 广告页面跳转
   */
  toAdPage(obj: string | AdPageObject) {
    // 统一处理参数格式
    const adObj = typeof obj === 'string' ? { url: obj, object_name: '' } : obj;

    // 添加运行时查询参数
    const runWithRouteQuerys = getRunWithRouteQuerys();
    adObj.url = addQueryToUrl(adObj.url, runWithRouteQuerys);

    // 检查是否隐藏导航栏
    const hideNavigationBar = !!getQueryString('hidenav', adObj.url);

    // 非静态页面直接跳转（后端会处理UA）
    if (adObj.object_name !== 'static' && adObj.object_name !== '') {
      window.location.href = adObj.url;
      return;
    }

    // 静态页面根据环境选择跳转方式
    if (this.isAppEnv()) {
      // APP环境：在新WebView中打开
      if (window.bridge) {
        window.bridge.openWebView({
          url: adObj.url,
          isCurrentPageOpen: 0,
          hideNavigationBar: hideNavigationBar ? 1 : 0,
        });
        return;
      }
    } else if (this.openInMiniProgram(adObj.url)) {
      // 小程序环境处理
      return;
    }

    // 默认处理：路由跳转或直接跳转
    if (adObj.path) {
      this.router.push(adObj.path);
    } else {
      window.location.href = adObj.url;
    }
  }

  /**
   * 跳转到聊天页面
   */
  toChat(id: string, options: { replace?: boolean } = {}) {
    const { replace = false } = options;
    const { isYixinliApp, isZiXunApp, isQingSuApp, isZiXunShiApp, isCikeApp } =
      getAppType();

    if (isYixinliApp || isZiXunApp || isQingSuApp || isCikeApp) {
      // 普通APP：使用协议跳转
      window.location.href = `yixinli://open_chat?user_id=${id}`;
    } else if (isZiXunShiApp && window.bridge) {
      // 咨询师APP：使用bridge跳转
      window.bridge.openAppPage({
        routeName: 'toYxlChat',
        param: JSON.stringify({ chatUserId: id }),
      });
    } else {
      // Web环境：跳转到聊天页面
      const { channel_flag = '', cid = '' } = this.route.query;
      const chatUrl = `https://m.xinli001.com/im_chat?user_id=${id}&cid=${cid}&channel_flag=${channel_flag}&hideNav=true`;

      if (replace) {
        this.replace(chatUrl);
      } else {
        this.push(chatUrl);
      }
    }
  }
}

// ==================== 单例模式 ====================

let routerInstance: RouterCore | null = null;

/**
 * 获取路由实例（单例）
 */
function getRouterCore(): RouterCore {
  if (!routerInstance) {
    routerInstance = new RouterCore();
  }
  return routerInstance;
}

// ==================== 导出方法 ====================

const router = getRouterCore();

// 基础路由方法
export const routerPush = router.push.bind(router);
export const routerReplace = router.replace.bind(router);
export const routerGoback = router.goback.bind(router);

// 扩展路由方法
export const routerPushWithoutNav = router.pushWithoutNav.bind(router);
export const routerToStatic = router.toStatic.bind(router);
export const routerToStaticWithoutNav = router.toStaticWithoutNav.bind(router);

// 业务路由方法
export const toLogin = router.toLogin.bind(router);
export const toAdPage = router.toAdPage.bind(router);
export const toChat = router.toChat.bind(router);

// 兼容性导出
export { getRouterCore };
